import {
  Module,
  NestModule,
  MiddlewareConsumer,
  RequestMethod
} from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { DbModule, RedisModule } from 'libs/db/src';
import { Role, User, Company, Employee, Department, Menu } from '@schemas';
import {
  UserModule,
  RoleModule,
  AuthModule,
  CompanyModule,
  EmployeeModule,
  DepartmentModule,
  MenuModule,
  UploadModule
} from '../modules';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CryptoService } from '../modules/crypto/crypto.service';
import { HashPasswordMiddleware } from '../app/hash-password/hash-password.middleware';
import swaggerConfig from '../common/config/swagger.config';
import { validateEnvironmentVariables } from '../common';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [swaggerConfig],
      validate: validateEnvironmentVariables
    }),
    DbModule.forRoot('MONGO_URI'),
    DbModule.forFeature([User, Role, Company, Employee, Department, Menu]),
    AuthModule,
    UserModule,
    DepartmentModule,
    MenuModule,
    RoleModule,
    RedisModule,
    CompanyModule,
    EmployeeModule,
    UploadModule
  ],
  controllers: [AppController],
  providers: [AppService, CryptoService]
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(HashPasswordMiddleware).forRoutes(
      {
        path: 'acl/user/create',
        method: RequestMethod.POST
      },
      {
        path: 'acl/user/update/*',
        method: RequestMethod.PATCH
      }
    );
  }
}
